import requestConfig from "@/uni_modules/kantboot-framework-uniapp/libs/request/request.config";
import request from "@/uni_modules/kantboot-framework-uniapp/libs/request";
import event from "@/uni_modules/kantboot-framework-uniapp/libs/event";
import userAccount from "@/uni_modules/kantboot-framework-uniapp/libs/userAccount"
import storage from "../storage";

let socket = null;

function generateMemory() {
    return new Promise((resolve, reject) => {
        request.send({
            uri: "/socket-websocket-web/websocket/createMemory",
            stateSuccess: (res) => {
                resolve(res.data);
            },
            stateFail: (res) => {
                reject(res.data);
            }
        });
    });
}

async function start() {
    await connectWebSocket();

    event.on("login:success", () => {
        connectWebSocket();
    })

    setInterval(() => {
        check();
    }, 2000);


}

let check = ()=>{
    let isLogin = userAccount.getIsLogin();
    console.log(isLogin, "用户登录状态", "WEBSOCKET 检测");
    console.log(socket.readyState,"WEBSOCKET socket.readyState");
    if (isLogin) {
        if(socket == null || !socket) {
            connectWebSocket();
            return;
        }
        if (socket.readyState === 1) {
            console.log("WebSocket connection started");
            // 如果比较上次心跳时间大于5秒，则发送心跳包
            let heartbeatTime = storage.get("websocket:heartbeat:lastTime");
            console.log(heartbeatTime,"WEBSOCKET 心跳时间");
            if(!heartbeatTime) {
                console.log("WEBSOCKET 发送心跳包");
                sendMessage({
                    operateCode: "heartbeat"
                });
                // 保存发送心跳时间
                let date = new Date().getTime();
                storage.set("websocket:heartbeat:lastTime", date);

            }
            else {
                let date = new Date().getTime();
                console.log(date - parseInt(heartbeatTime),"WEBSOCKET 心跳时间差");
                if (date - parseInt(heartbeatTime) >= 5000) {
                    console.log("WEBSOCKET 发送心跳包");
                    sendMessage({
                        operateCode: "heartbeat"
                    });
                    // 保存发送心跳时间
                    date = new Date().getTime();
                    storage.set("websocket:heartbeat:lastTime", date);
                }
            }

            return;
        }
        if (socket.readyState === 3) {
            console.log("WebSocket connection closed");
            connectWebSocket();
            return;
        }
    }else{
        if(!socket) {
            return;
        }
        if (socket.readyState === 1) {
            console.log("WebSocket connection started");
            closeWebSocket();
            return;
        }
        if (socket.readyState === 3) {
            console.log("WebSocket connection closed");
            return;
        }
    }
}

/**
 * 连接WebSocket
 */
let connectWebSocket = async () => {
    // 先关闭
    try {
        closeWebSocket();
    } catch (e) {
    }

    let memory = "";
    await generateMemory().then((res) => {
        memory = res;
    }).catch((res) => {
        console.log("WEBSOCKET 生成记忆体失败", res);
        // console.error(res);
    });
    console.log("WEBSOCKET 连接WebSocket", memory);
    // 如果没有记忆体，就断开
    if (!memory) {
        return;
    }

    socket = uni.connectSocket({
        url: `${requestConfig.websocketAddress}/${memory}`, // 你的WebSocket服务器地址
        complete: (res) => {
            console.log('WEBSOCKET 连接结果', res);
        }
    });


    // let heartbeatInterval = setInterval(() => {
    //     sendMessage({
    //         operateCode: "heartbeat"
    //     });
    // }, 5000);

    // 监听WebSocket事件
    uni.onSocketOpen((res) => {
        console.log('WEBSOCKET 连接已打开！', res);
    });
    uni.onSocketError((res) => {
        console.log('WEBSOCKET 连接打开失败，请检查！', res);
        try {
            // clearInterval(heartbeatInterval);
            closeWebSocket();
        } catch (e) {
        }
    });
    uni.onSocketMessage((res) => {
        console.log('WEBSOCKET 收到服务器内容：', res.data);
        let isLogin = userAccount.getIsLogin();
        if(!isLogin) {
            console.log("WEBSOCKET 忽略处理");
            return;
        }
        // operateCode:"heartbeat"
        let json = JSON.parse(res.data);
        if (json.dataStr != null && json.dataStr) {
            json.data = JSON.parse(json.dataStr);
        }
        event.emit(json.emit, json.data);
    });
    uni.onSocketClose((res) => {
        console.log('WEBSOCKET已关闭！', res);
        try {
            // clearInterval(heartbeatInterval);
        } catch (e) {
        }
    });

}

// 发送消息
function sendMessage(message) {
    uni.sendSocketMessage({
        data: JSON.stringify(message),
        success: (res) => {
            console.log('WEBSOCKET 心跳包 发送成功', res);
        },
        fail: (res) => {
            console.log('WEBSOCKET 心跳包 发送失败', res);
        }
    });
}

// 关闭WebSocket连接
function closeWebSocket() {
    uni.closeSocket();
}

export default {
    start,
    connectWebSocket,
    sendMessage,
    closeWebSocket
}
